package ca.etsmtl.log320lab1;

import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Encode {

	FileReader _fileReader;
	ObjectOutputStream _fileWriter;
	String[] _encryptionTable;
	public Encode(FileReader fileReader, ObjectOutputStream fileWriter, String[] encryptionTable){
		_fileReader = fileReader;
		_fileWriter = fileWriter;
		_encryptionTable = encryptionTable;
	}
	public void writeDecodeInformation(int[] frequencyTable) throws IOException
	{
		for (int i = 0; i < frequencyTable.length; i++) {
			if (frequencyTable[i] != 0) {
				_fileWriter.write(i);
				_fileWriter.write(frequencyTable[i]);
			}
		}
		_fileWriter.write(0);
		_fileWriter.write(0);
	}
	public Boolean createEncodeFile(int[] frequencyTable) throws IOException
	{
		writeDecodeInformation(frequencyTable);
		if (_fileReader == null || _fileWriter == null ) {
			return false;
		}
		int read = _fileReader.read();
		int nbBit = 0;
		String encryptionToWrite = "";
		byte toWrite = 0;
		int subStringValue = 0;
		while (read != -1) {
			encryptionToWrite = _encryptionTable[read];
			    while(encryptionToWrite.length() > 0) 
			    {
			      for(int i = 0; i < encryptionToWrite.length() && i < 8  ; i++)
			      {
			        toWrite <<= 1; 
			        if(encryptionToWrite.charAt(i) == '1') 
			          toWrite++;
			          
			        subStringValue ++;
			        nbBit++;
			        if (nbBit == 8) {
			        	if (toWrite <0)
			        		_fileWriter.write(256 + toWrite);
			        	else
			        		_fileWriter.write((char)toWrite);
					      toWrite = 0; 
					      nbBit=0;
					}
			      }     
			      encryptionToWrite = encryptionToWrite.substring(subStringValue);     
			      subStringValue = 0;
			    } 
			    
			read = _fileReader.read();
		}	
		if (nbBit > 0) {
			 for(int i = 0; i < 8-nbBit  ; i++)
		        toWrite <<= 1; 
       	if (toWrite <0)
      		_fileWriter.write(256 + toWrite);
      	else
      		_fileWriter.write((char)toWrite);
		}
		_fileReader.close();
		_fileWriter.close();
		return true;
	}
}
